﻿using Ay.Framework.WPF;
using Ay.Framework.WPF.Controls;
using MPSystem.Models;
using Base.BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Visifire.Charts;
using Base.DAL;
using MPSystem.Views.YFQ;
using MPSystem.Controllers;
using Base.Util;

namespace ADX.Views
{
    /// <summary>
    /// ZCYLPage.xaml 的交互逻辑
    /// </summary>
    public partial class ZCYLPage : Page
    { 
        //通用类
        Common common = new Common();
        bool FirstLoadChart = true;
        bool FirstLoadWarn = true;
        int times = 5;//默认刷新时间分钟
        System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
        private List<double> P1 = new List<double>() { 11, 12, 12, 3, AyCommon.Rnd.Next(1, 33) };
        private List<double> P2 = new List<double>() { 33, 14, 1, AyCommon.Rnd.Next(1, 33), 34 };
        private List<double> P3 = new List<double>() { 22, 33, AyCommon.Rnd.Next(1, 33), 33, 22 };
        private List<string> X = new List<string>() { "1", "1", "1", "1", "1" };
        private List<double> P12 = new List<double>();
        private List<string> S = new List<string>() { "1", "1", "1", "1", "1" };
        private List<double> F1 = new List<double>();
        private List<double> F2 = new List<double>();
        private List<double> F3 = new List<double>();
        private List<double> F12 = new List<double>();
        private List<double> Freq = new List<double>();
        private List<DateTime> T = new List<DateTime>();

        private double UpperLimit = 40;//上限值
        private double LowLimit = 20;//下限值
        private double WarnLimit = 35;//报警值
        private bool WaveWarn = false;//声音报警
        private bool[] Channel = new bool[] { true,true,true};
        private string ComanpyName = "";

        private bool _IsBusy = true;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set { _IsBusy = value; }
        }
        public ZCYLPage()
        {
            InitializeComponent();
            Loaded += AyPage_Loaded;
        }

        void AyPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= AyPage_Loaded;
            try
            {
                dt.Tick += new EventHandler(timeCycle);
                dt.Interval = new TimeSpan(0, 0, 0, times, 0); //TimeSpan.FromSeconds(times);
                dt.Start();
                ComanpyName = common.GetCompanyName();
                T_CompayName.Text = ComanpyName + "综采工作阻力在线监测";
                var rcq = ConfigService.GetCQ(true);
                if (rcq.Count() == 0)
                {
                    AyMessageBox.ShowError("没有测区！");
                    return;
                }
                combcq.ItemsSource = rcq;
                combcq.SelectedIndex = 0;
                //工作面
                var rgzm = ConfigService.GetGZM(rcq.ElementAt(0).CQBH);
                combgzm.ItemsSource = common.LoadCombox_IECobx(rgzm);
                if (rgzm.Count() > 0) combgzm.SelectedIndex = 1;
                //开始的时候，打开所有COM口

                //ComService.cs.Start();//如果运行错误
                string aa = ComService.cs.LastError;
                if (aa.Length > 0)
                    AyMessageBox.ShowError("COM口打开错误！！" + aa);
            }
            catch (Exception ex) { }
        }

        public void timeCycle(object sender, EventArgs e)
        {
            times = (int)slider.Value;
            dt.Interval = new TimeSpan(0, 0, 0, times, 0);
            SycnReflash();
        }
        private void LayoutRoot_load(object sender, EventArgs e)
        {

            SycnReflash();
        }

        int xtemp = 0;
        /// <summary>
        /// 后台加载
        /// </summary>
        void SycnReflash()
        {
            //LoggerHelper.Info("界面刷新，测区选择值："+ combcq.SelectedValue+",工作面选择值："+ combgzm.SelectedValue);            
            if (combcq.SelectedValue == null || combgzm.SelectedValue == null) return;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, ea) =>
            {
                //no direct interaction with the UI is allowed from this method
                AyThread.Instance.RunUI(() =>
                {
                    int cq = AyCommon.ToInt(combcq.SelectedValue.ToString());
                    int gzm = AyCommon.ToInt(combgzm.SelectedValue.ToString());
                    DataZcService ds = new DataZcService();
                    var r = ds.GetActive(cq, gzm);
                    if (r.WarnNow)
                    {
                        if(WaveWarn)
                            System.Media.SystemSounds.Exclamation.Play();
                        btnAttac_Click(null, null);
                    }
                    
                    P1 = r.P1;
                    P2 = r.P2;
                    P3 = r.P3;
                    X = r.X;
                    P12 = r.P12;
                    S = r.S;
                    T = r.T;
                    //LoggerHelper.Info("界面刷新,时间记录总数：" + r.T.Count);
                    //foreach (var t_value in T)
                    //    LoggerHelper.Info("界面刷新，当前时间:" + t_value.ToString());
                    F1 = r.F1;
                    F2 = r.F2;
                    F3 = r.F3;
                    F12 = r.F12;
                    Freq = r.Freq;
                    
                    //int count_P1 = 0;
                    //LoggerHelper.Info("界面刷新,P1总数：" +r.P1.Count);
                    //for (int i=0;i<P1.Count;i++)
                    //    LoggerHelper.Info("界面刷新：P1的值:" + P1[i].ToString()+",时间"+T[i]);

                    /*动态更新下方控件*/
                    var wzs = ConfigService.GetZcWzEnabled(gzm);
                    UpdateGrid(wzs, S);
                    if (ck.IsChecked == true)
                    {
                        CreateChartColumn("压力（Mpa)", X, P1, P2, P3);
                    }
                    else
                    {
                        CreateChartStackedColumn("压力（Mpa)", X, P1, P2, P3);
                    }
                });
                //CreateChartColumn("测试", strListx, strListy);
            };
            worker.RunWorkerCompleted += (o, ea) =>
            {
                //work has completed. you can now interact with the UI           
                busyin.IsBusy = false;
            };
            //set the IsBusy before you start the thread
            busyin.IsBusy = true;
            worker.RunWorkerAsync();
        }

        private void btnquery_Click(object sender, RoutedEventArgs e)
        {
            SycnReflash();
        }

        private void DrawBase()
        {
            if (FirstLoadChart)
            {
                //是否启用打印和保持图片
                chart.ToolBarEnabled = true;
                chart.AnimationEnabled = false;

                chart.Background = new SolidColorBrush(Colors.LightBlue);
                Axis xAxis = new Axis();
                xAxis.Enabled = true;
                AxisLabels xLabel = new AxisLabels();
                xLabel.Angle = -45;
                xAxis.AxisLabels = xLabel;
                chart.AxesX.Add(xAxis);

                //设置图标的属性
                chart.ScrollingEnabled = true;//是否启用或禁用滚动
                chart.View3D = false;//3D效果显示

                //创建一个标题的对象
                Title title = new Title();

                //设置标题的名称
                title.Text = Name;
                // title.Padding = new Thickness(0, 10, 5, 0);

                //向图标添加标题
                chart.Titles.Add(title);

                Axis yAxis = new Axis();
                //设置图标中Y轴的最小值永远为0           
                yAxis.AxisMinimum = 0;
                yAxis.AxisMaximum = 60;
                //设置图表中Y轴的后缀          
                yAxis.Suffix = "Mpa";
                //间隔为10MPa
                yAxis.Interval = 10;
                chart.AxesY.Add(yAxis);
                FirstLoadChart = false;
            }
            else
            {
                chart.Series.Clear();
            }
        }
        private void DrawWarn()
        {
            if (FirstLoadWarn)
            {
                chart.TrendLines.Clear();
                //TrendLine tl = new TrendLine();
                //tl.Value = UpperLimit;
                //tl.LineThickness = 1;
                //tl.LineStyle = LineStyles.Dashed;
                //tl.LabelText = "上限值";
                //tl.LineColor = new SolidColorBrush(Colors.LightBlue);
                //chart.TrendLines.Add(tl);

                TrendLine t2 = new TrendLine();
                t2.Value = LowLimit;
                t2.LineThickness = 1;
                t2.LineStyle = LineStyles.Dashed;
                t2.LabelText = "下限值";
                t2.LineColor = new SolidColorBrush(Colors.DarkBlue);
                chart.TrendLines.Add(t2);
                FirstLoadWarn = false;

                TrendLine t3 = new TrendLine();
                t3.Value = WarnLimit;
                t3.LineThickness = 1;
                t3.LineStyle = LineStyles.Dashed;
                t3.LabelText = "报警值";
                t3.LineColor = new SolidColorBrush(Colors.DarkRed);
                chart.TrendLines.Add(t3);
                FirstLoadWarn = false;
            }
        }
        public void CreateChartColumn(string name, List<string> valuex, List<double> valuey0, List<double> valuey1, List<double> valuey2)
        {
            List<double> valuey = new List<double>();
            //创建一个图标
            //   Chart chart = new Chart();
            DrawBase();
            for (int ii = 1; ii <= 3; ii++)
            {
                DataSeries oneDataSeries = new DataSeries();
                //oneDataSeries.LegendText = "Philadelphia";
                oneDataSeries.RenderAs = RenderAs.Column;

                bool channelUsed = false;
                if (ii == 1 && Channel[0])
                {
                    oneDataSeries.Color = new SolidColorBrush(Colors.Orange);
                    oneDataSeries.LegendText = "P1";
                    valuey = valuey0;
                    channelUsed = true;
                }
                else if (ii == 2 && Channel[1])
                {
                    oneDataSeries.Color = new SolidColorBrush(Colors.Pink);
                    oneDataSeries.LegendText = "P2";
                    valuey = valuey1;
                    channelUsed = true;
                }
                else if (ii == 3 && Channel[2])
                {
                    oneDataSeries.Color = new SolidColorBrush(Colors.LightGreen);
                    oneDataSeries.LegendText = "P3";
                    valuey = valuey2;
                    channelUsed = true;
                }
                if(!channelUsed)
                {
                    continue;
                }
                // 创建一个新的数据线。               
                //DataSeries dataSeries = new DataSeries();

                //// 设置数据线的格式
                //dataSeries.RenderAs = RenderAs.StackedColumn;//柱状Stacked

                // 设置数据点              

                //创建第一个DataSeries

                //创建第一个DataSeries的DataPoint
                DataPoint oneDataPoint = null;
                for (int i = 0; i < valuey.Count; i++)
                {
                    oneDataPoint = new DataPoint();
                    oneDataPoint.AxisXLabel = valuex[i];
                    var y = valuey[i];

                    oneDataPoint.YValue = y;
                    oneDataSeries.LabelEnabled = true;
                    //oneDataSeries.LabelText = "#YValue";

                    oneDataSeries.DataPoints.Add(oneDataPoint);
                }
                chart.Series.Add(oneDataSeries);
            }
            DrawWarn();
            // 添加数据线到数据序列。                
            // chart.Series.Add(dataSeries);

            //将生产的图表增加到Grid，然后通过Grid添加到上层Grid.           
            //Grid gr = new Grid();
            //gr.Children.Add(chart);
            //  XX.Children.Add(chart);

        }
        public void CreateChartStackedColumn(string name, List<string> valuex, List<double> valuey0, List<double> valuey1, List<double> valuey2)
        {

            List<double> valuey = new List<double>();
            //创建一个图标
            //Chart chart = new Chart(); 

            this.chart.Series.Clear();
            
            for (int ii = 0; ii < valuey0.Count; ii++)
            {

                valuey.Add(valuey0[ii]);
                valuey.Add(valuey1[ii]);
                valuey.Add(valuey2[ii]);
            }

            // 设置数据点              

            //创建第一个DataSeries
            DataSeries oneDataSeries = new DataSeries();
            oneDataSeries.LegendText = "下限值";
            oneDataSeries.LabelEnabled = true;
            oneDataSeries.RenderAs = RenderAs.StackedColumn;
            oneDataSeries.Color = new SolidColorBrush(Colors.LightYellow);
            //创建第一个DataSeries的DataPoint
            DataPoint oneDataPoint = null;
            int x1 = 0, x2 = 0, x3 = 0;
            for (int i = 0; i < valuey.Count; i++)
            {
                if (!Channel[i % 3]) continue;
                oneDataPoint = new DataPoint();
                if (i % 3 == 0)
                {
                    //oneDataPoint.Margin = new System.Windows.Thickness((double)1000);

                    oneDataPoint.AxisXLabel = valuex[x1];
                    x1++;
                }
                else { oneDataPoint.AxisXLabel = ""; }

                var y = valuey[i];
                if (y > LowLimit)
                {
                    oneDataPoint.YValue = LowLimit;
                }
                else
                {
                    oneDataPoint.YValue = y;

                    //oneDataSeries.LabelText = "#YValue";
                }
                oneDataSeries.DataPoints.Add(oneDataPoint);
            }
            chart.Series.Add(oneDataSeries);

            //创建第二个DataSeries
            DataSeries twoDataSeries = new DataSeries();
            twoDataSeries.LegendText = "正常值";
            //twoDataSeries.LegendText = "Phoenix";
            twoDataSeries.RenderAs = RenderAs.StackedColumn;
            twoDataSeries.Color = new SolidColorBrush(Colors.LightBlue);
            //创建第二个DataSeries的DataPoint
            DataPoint twoDataPoint = null;
            for (int i = 0; i < valuey.Count; i++)
            {
                if (!Channel[i % 3]) continue;
                twoDataPoint = new DataPoint();
                if (i % 3 == 1)
                {
                    //oneDataPoint.Margin = new System.Windows.Thickness((double)1000);

                    twoDataPoint.AxisXLabel = valuex[x2];
                    x2++;
                }
                else { twoDataPoint.AxisXLabel = ""; }
                var y = valuey[i];
                twoDataSeries.LabelEnabled = false;
                if (y > LowLimit)
                {
                    y = y>UpperLimit?UpperLimit:y;
                    twoDataPoint.YValue = y-LowLimit;
                }
                else
                {
                    twoDataPoint.YValue = 0;
                }
                twoDataSeries.DataPoints.Add(twoDataPoint);
            }
            chart.Series.Add(twoDataSeries);

            //创建第三个DataSeries
            DataSeries threeDataSeries = new DataSeries();
            threeDataSeries.RenderAs = RenderAs.StackedColumn;

            threeDataSeries.LegendText = "上限值";
            threeDataSeries.Color = new SolidColorBrush(Colors.LightPink);
            //创建第三个DataSeries的DataPoint
            DataPoint threeDataPoint = null;
            for (int i = 0; i < valuey.Count; i++)
            {
                if (!Channel[i % 3]) continue;
                threeDataPoint = new DataPoint();
                if (i % 3 == 2)
                {
                    //oneDataPoint.Margin = new System.Windows.Thickness((double)1000);

                    threeDataPoint.AxisXLabel = valuex[x3];
                    x3++;
                }
                else { threeDataPoint.AxisXLabel = ""; }
                var y = valuey[i];
                //threeDataSeries.LabelText = valuey[i].ToString()+"Mpa";
                threeDataSeries.LabelEnabled = false;
                if (y >= UpperLimit)
                {
                    threeDataPoint.YValue = y - UpperLimit;
                }
                else
                {
                    threeDataPoint.YValue = 0;
                }
                threeDataSeries.LabelText = valuey[i].ToString();
                //threeDataPoint.YValue =  (valuey[i]);
                threeDataSeries.DataPoints.Add(threeDataPoint);
            }
            chart.Series.Add(threeDataSeries);

            DrawWarn();
            // 添加数据线到数据序列。                
            // chart.Series.Add(dataSeries);

            //将生产的图表增加到Grid，然后通过Grid添加到上层Grid.           
            //Grid gr = new Grid();
            //gr.Children.Add(chart);
            // XX.Children.Add(chart);

            //AyThread.Instance.Sleep(2 * 1000); //加上这一句试试
            //busyin.IsBusy = false;
        }

        private void ck_Checked(object sender, RoutedEventArgs e)
        {
            SycnReflash();
        }

        private void ck_Unchecked(object sender, RoutedEventArgs e)
        {
            SycnReflash();
        }

        /// <summary>
        /// 附加信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAttac_Click(object sender, RoutedEventArgs e)
        {
            int cqbh = combcq.SelectedValue.ToInt();
            int gzmbh = combgzm.SelectedValue.ToInt();
            if (cqbh==0 || gzmbh==0)
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            ZCYLPage_Attac.parent = "zc";
            ZCYLPage_Attac.cqbh = cqbh;
            ZCYLPage_Attac.gzmbh = gzmbh;
            ShowNavigationWindow("检测报表--附加信息", "/Views/YFQ/ZCYLPage_Attac.xaml", 600, 500);
        }

        /// <summary>/// 弹出层对象/// </summary>

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height)
        {
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing; window.Content = new ZCYLPage_Attac();
                // window.pas += new window.PassValuesHandler(ReceiveValues);
            }
            else if(window.Content!=null)
            {
                ((ZCYLPage_Attac)window.Content).LoadData();
            }
            if(!window.IsVisible)
                window.Show();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            window.Hide();
            e.Cancel = true;
        }
        /// <summary>
        /// 打开测区判断（指定测区COM口）
        /// </summary>
        private void OpenCQBH(int cqbh)
        {

            if (!MPLoginController.CurUser.IsRemote && !ComService.cs.OpenPort(cqbh))
                AyMessageBox.ShowError("测区编号打开错误！！" + ComService.cs.LastError);

        }
        /// <summary>
        /// 测区改变的时候，判断串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void combcq_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combcq.SelectedValue == null) return;
            int cqbh = AyCommon.ToInt(combcq.SelectedValue);
            if (!ComService.cs.IsOpen(cqbh)) OpenCQBH(cqbh);
            var gzmSource = ConfigService.GetGZM(cqbh);
            combgzm.ItemsSource = common.LoadCombox_IECobx(gzmSource);
            if (gzmSource.Count() > 0) combgzm.SelectedIndex = 1;
        }
        
        private void Combgzm_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combgzm.SelectedValue == null) return;
            int cqbh = AyCommon.ToInt(combcq.SelectedValue);
            int gzmbh = AyCommon.ToInt(combgzm.SelectedValue);
            //更新上限、下限、报警值
            var cs = ConfigService.FindZc(cqbh,gzmbh);
            if (cs != null)
            {
                UpperLimit = cs.YLSX;
                LowLimit = cs.YLXX;
                WarnLimit = cs.YLBJZ;
                Channel[0] = cs.FIRSTTD != "不使用";
                Channel[1] = cs.SECONDTD != "不使用";
                Channel[2] = cs.THIRDTD != "不使用";
                WaveWarn = cs.WAVEBJ;
                FirstLoadWarn = true;
            }
            var wzs = ConfigService.GetZcWzEnabled(gzmbh);
            UpdateGrid(wzs, null);
        }

        private void UpdateGrid(IEnumerable<ZCYLFJWZB> wzs, List<string> S)
        {
            try
            {
                bord1.Child = null;
                Grid grid1 = new Grid();
                // grid1.Children.Clear();
                RowDefinition row1 = new RowDefinition();   //实例化一个Grid行
                grid1.RowDefinitions.Add(row1);
                RowDefinition row2 = new RowDefinition();   //实例化一个Grid行
                grid1.RowDefinitions.Add(row2);
                RowDefinition row3 = new RowDefinition();   //实例化一个Grid行
                grid1.RowDefinitions.Add(row3);
                for (int i = 0; i < wzs.Count() + 1; i++)
                {
                    ColumnDefinition column = new ColumnDefinition();
                    grid1.ColumnDefinitions.Add(column);
                }

                Brush error = new SolidColorBrush(Colors.DarkRed);
                Brush warn = new SolidColorBrush(Colors.LightGray);
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < wzs.Count() + 1; j++)
                    {
                        Border bor = new Border();
                        bor.BorderBrush = new SolidColorBrush(Colors.LightGray);
                        bor.BorderThickness = new Thickness(1);
                        bor.HorizontalAlignment = HorizontalAlignment.Stretch;
                        bor.VerticalAlignment = VerticalAlignment.Stretch;
                        TextBlock tb = new TextBlock();
                        tb.HorizontalAlignment = HorizontalAlignment.Center;
                        tb.VerticalAlignment = VerticalAlignment.Center;
                        if (j == 0 && i == 0)
                            tb.Text = "编号";
                        else if (j == 0 && i == 1)
                            tb.Text = "位置";
                        else if (j == 0 && i == 2)
                            tb.Text = "状态";
                        else if (i == 0)
                            tb.Text = wzs.ElementAt(j - 1).YLFJBH.ToString();
                        else if (i == 1)
                            tb.Text = wzs.ElementAt(j - 1).WZ;
                        else if (i == 2)
                        {
                            if (S == null || S.Count == 0)
                                tb.Text = "-";
                            else
                            {
                                tb.Text = S[j - 1];
                                if(S[j - 1] == "故障")
                                    tb.Foreground = error;
                                else if (S[j - 1] == "离线")
                                    tb.Foreground = warn;
                            }
                        }
                        bor.Child = tb;
                        Grid.SetColumn(bor, j);
                        Grid.SetRow(bor, i);

                        grid1.Children.Add(bor);
                    }
                    bord1.Child = grid1;
                    // grid1.ShowGridLines = true;
                }
            }
            catch (Exception EX)
            {

            }
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            dt.Stop();
            if (window!=null)
                window.Hide();
        }
    }
}
